<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

/**
 * 支付控制器
 *
 */
class PayController extends HomeController
{
    /**
     * 当面付花呗支付回调地址
     */
    public function huabei_notify()
    {
        /* ceshi 数据**/
//       $data = file_get_contents('php://input');
//       $data = json_decode($data, true);
//       $_POST = $data;
        /***/

        $data = $_POST;
        $time = time();

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 当面付花呗回调数据: ' . json_encode($data) . PHP_EOL, FILE_APPEND);
        if ($data['trade_status'] == 'TRADE_SUCCESS') {//交易成功
            // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；3、将口碑商户扣取费率后的余额转入企业支付宝
            $danhao = $_POST['out_trade_no'];
            $one = M('dingdan')->where(['danhao' => $danhao])->find();
            $shoukuanma_id = $one['shoukuanma_id'];

            if ($one['status'] == 1) {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态已修改' . PHP_EOL, FILE_APPEND);
                echo success;
            } else {
                $trade_no = $_POST['trade_no'];
                $buyer = $_POST['buyer_logon_id'];
                $seller = $_POST['seller_email'];
                $money = $_POST['total_amount'];
                $seller_id = $_POST['seller_id'];
                $buyer_id = $_POST['buyer_id'];
                // gather
                $uid = $one['uid'];
                $gather = M('gather')->where(['uid' => $uid])->find();

                if ($one['hk'] == 1) {
                    $yh_money = $money * (100 - $gather['up_set']) / 100;
                } else {
                    //修改为： 订单收益 = 订单金额 × （回款费率 - （上级设定费率+分额度累加费率））
                    $selfRate = \Home\Model\PtdataModel::getUserTdRate('hbtd',$uid,$money);
                    if(empty($selfRate)){
                        $selfRate = 0;
                    }
                    $yh_money = $money * ($gather['path6'] - $selfRate) / 100;

                }

                // 1、将订单状态修改为成功
                $id1 = M('dingdan')->where(['danhao' => $danhao])->save([
                    'trade_no' => $trade_no,
                    'buyer' => $buyer,
                    'seller' => $seller,
                    'seller_id' => $seller_id,
                    'status' => 1,
                    'pay_money' => $money,
                    'tx' => 0,
                    'yh_money' => $yh_money,
                    'buyer_id' => $data['buyer_id'],

                ]);

                if ($id1 > 0) {
                    // 2、修改平台用户的余额；
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态修改成功' . PHP_EOL, FILE_APPEND);


//                    if ($one['hk'] == 1) {
//                        $total = $gather['money'] + $money * (100 - $gather['up_set']) / 100;
//                    } else {
//                        $total = $gather['money'] + $money * ($gather['path6'] - $gather['up_set']) / 100;
//                    }
//
//                    M('dingdan')->where(['danhao' => $danhao])->save([
//                        't_money' => $total
//                    ]);

                    // $total=$gather['money']+$money*(1-$gather['path1']/100);

                    //码商应该拿=套现金额（一级分润-共码费率）
                    $kbsh = M('kbsh')->where(['user_id' => $seller_id])->find();
                    $sh_money = price_format($money * ($kbsh['rate']/100 - $kbsh['rate2']/100));

                    put_file('马商分拥：',$sh_money);
                    $yongjin = ($gather['yongjin']*100 + $sh_money*100)/100;
                    $id2 = M('gather')->where(['uid' => $kbsh['uid']])->save(['yongjin' => price_format($yongjin)]);
                    put_file('增加分用：',M('gather')->getLastSql());
                    if ($id2 !== false) {
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                        if ($one['hk'] == 1) {
                            //不回款不需制定
                        } else {
                            // 插播：制定对应的转账表
//                    $trans_money = $money * (1 - $gather['path6'] / 100);
                            //修改为 收款码设置的费率

                            //取出收款码回款费率
                            $shoukuanma = M('shoukuanma')->find($shoukuanma_id);
                            $ptdata = M('ptdata')->find(1);

                            $trans_money = $money * (1 - $shoukuanma['hb'] / 100) - $ptdata['xyk_fee'];
                            $trans_money = number_format($trans_money, 2, '.', '');
                            $out_biz_no = 'hb' . date("YmdHis") . rand(1000, 9999);
                            $returninfo = [
                                'order_info' => $one,
                                'shoukuanma_id' => $shoukuanma_id,
                                'shoukuanma' => $shoukuanma,
                                'transmoney' => $trans_money
                            ];
//                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款金额信息：' . json_encode($returninfo) . PHP_EOL, FILE_APPEND);

                            $trans_result = M('trans')->add([
                                'trade_no' => $trade_no,
                                'uid' => $uid,
                                'money' => $trans_money,
                                'buyer_id' => $buyer_id,
                                'out_biz_no' => $out_biz_no
                            ]);

                            if ($trans_result) {

                                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入成功' . PHP_EOL, FILE_APPEND);
                            } else {
                                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入失败' . PHP_EOL, FILE_APPEND);
                            }
                        }


                        // 3、制定分账信息  通过seller在口碑商户表中找到使用的授权令牌



                        $id3 = M('split')->add([
                            'uid' => $kbsh['uid'],
                            'seller_id' => $seller_id,
                            'money_in' => $money,
                            'trade_no' => $trade_no,
                            't_money' => $money,
                            'sh_money' => $sh_money,
                            'sub_msg' => '',
                            'status' => 1,
                            'time' => time()

                        ]);
                        if ($id3 > 0) {
                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入成功' . PHP_EOL, FILE_APPEND);
                            // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%
                            $ptyh = M('ptyh')->find(['uid' => $one['uid']]);

                            //分润

                            echo success;

                            self::settle2admin($trade_no, $seller_id, $money, $uid, 'huabei',$shoukuanma_id);
                            self::settle2user($trade_no, $seller_id, $money, $uid, $shoukuanma_id, 'huabei',$buyer_id);
                            $this->divide($danhao);





                        } else {
                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入失败' . PHP_EOL, FILE_APPEND);

                            echo fail;
                        }

                    } else {
//                        echo M('gather')->getLastSql();
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '平台用户余额修改失败' . PHP_EOL, FILE_APPEND);

                        echo fail;
                    }
                } else {
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '订单状态修改失败' . PHP_EOL, FILE_APPEND);
                    echo M('dingdan')->getLastSql();

                    echo fail;
                }
            }

        }

    }

    /**
     * 风控花呗支付回调地址（手机网站支付付款方式花呗）
     */
    public function fengkonghuabei_notify()
    {
        /* ceshi 数据**/
//       $data = file_get_contents('php://input');
//       $data = json_decode($data, true);
//       $_POST = $data;
        /***/

        $data = $_POST;
        $time = time();

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 当面付花呗回调数据: ' . json_encode($data) . PHP_EOL, FILE_APPEND);
        if ($data['trade_status'] == 'TRADE_SUCCESS') {//交易成功
            // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；3、将口碑商户扣取费率后的余额转入企业支付宝
            $danhao = $_POST['out_trade_no'];
            $one = M('dingdan')->where(['danhao' => $danhao])->find();
            $shoukuanma_id = $one['shoukuanma_id'];

            if ($one['status'] == 1) {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态已修改' . PHP_EOL, FILE_APPEND);
                echo success;
            } else {
                $trade_no = $_POST['trade_no'];
                $buyer = $_POST['buyer_logon_id'];
                $seller = $_POST['seller_email'];
                $money = $_POST['total_amount'];
                $seller_id = $_POST['seller_id'];
                $buyer_id = $_POST['buyer_id'];
                // gather
                $uid = $one['uid'];
                $gather = M('gather')->where(['uid' => $uid])->find();

                if ($one['hk'] == 1) {
                    $yh_money = $money * (100 - $gather['up_set']) / 100;
                } else {
                    //修改为： 订单收益 = 订单金额 × （回款费率 - （上级设定费率+分额度累加费率））
//                    $levelRate = 0;
//                    if ($money >= 400 && $money < 600) {
//                        $levelRate = 0.8;
//                    } elseif ($money >= 600 && $money < 5000) {
//                        $levelRate = 1.6;
//                    } else {
//                        $levelRate = 0;
//                    }
//
//                    $yh_money = $money * ($gather['path6'] - ($gather['up_set'] + $levelRate)) / 100;

                    $selfRate = \Home\Model\PtdataModel::getUserTdRate('fkhbtd',$uid,$money);
                    if(empty($selfRate)){
                        $selfRate = 0;
                    }
                    $yh_money = $money * ($gather['path6'] - $selfRate) / 100;

                }

                // 1、将订单状态修改为成功
                $id1 = M('dingdan')->where(['danhao' => $danhao])->save([
                    'trade_no' => $trade_no,
                    'buyer' => $buyer,
                    'seller' => $seller,
                    'seller_id' => $seller_id,
                    'status' => 1,
                    'pay_money' => $money,
                    'tx' => 0,
                    'yh_money' => $yh_money,
                    'dingdan_id' => $one['id']
                ]);

                if ($id1 > 0) {
                    // 2、修改平台用户的余额；
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态修改成功' . PHP_EOL, FILE_APPEND);


                    if ($one['hk'] == 1) {
                        $total = $gather['money'] + $money * (100 - $gather['up_set']) / 100;
                    } else {
                        $total = $gather['money'] + $money * ($gather['path6'] - $gather['up_set']) / 100;
                    }

                    M('dingdan')->where(['danhao' => $danhao])->save([
                        't_money' => $total
                    ]);

                    // $total=$gather['money']+$money*(1-$gather['path1']/100);

                    if (true) {
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                        if ($one['hk'] == 1) {
                            //不回款不需制定
                        } else {
                            // 插播：制定对应的转账表
//                    $trans_money = $money * (1 - $gather['path6'] / 100);
                            //修改为 收款码设置的费率

                            //取出收款码回款费率


                            $shoukuanma = M('shoukuanma')->find($shoukuanma_id);
                            $ptdata = M('ptdata')->find(1);
                            $trans_money = $money * (1 - $shoukuanma['hb'] / 100) - $ptdata['xyk_fee'];
                            $trans_money = number_format($trans_money, 2, '.', '');
                            $out_biz_no = 'hb' . date("YmdHis") . rand(1000, 9999);
                            $returninfo = [
                                'order_info' => $one,
                                'shoukuanma_id' => $shoukuanma_id,
                                'shoukuanma' => $shoukuanma,
                                'transmoney' => $trans_money
                            ];
//                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款金额信息：' . json_encode($returninfo) . PHP_EOL, FILE_APPEND);

                            $trans_result = M('trans')->add([
                                'trade_no' => $trade_no,
                                'uid' => $uid,
                                'money' => $trans_money,
                                'buyer_id' => $buyer_id,
                                'out_biz_no' => $out_biz_no
                            ]);

                            if ($trans_result) {

                                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入成功' . PHP_EOL, FILE_APPEND);
                            } else {
                                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入失败' . PHP_EOL, FILE_APPEND);
                            }
                        }


                        // 3、制定分账信息  通过seller在口碑商户表中找到使用的授权令牌
//                        $id3 = M('split')->add([
//                            'seller_id' => $seller_id,
//                            'money_in' => $money,
//                            'trade_no' => $trade_no
//                        ]);
                        if (true) {
//                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入成功' . PHP_EOL, FILE_APPEND);


                            // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%
                            $ptyh = M('ptyh')->find(['uid' => $one['uid']]);

                            //分润

                            echo success;

                            self::settle2admin($trade_no, $seller_id, $money, $uid, 'fkhb',$shoukuanma_id);
                            self::settle2user($trade_no, $seller_id, $money, $uid, $shoukuanma_id, 'fkhb',$buyer_id);
                            $this->divide($danhao);



                        } else {
                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入失败' . PHP_EOL, FILE_APPEND);

                            echo fail;
                        }

                    } else {
//                        echo M('gather')->getLastSql();
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '平台用户余额修改失败' . PHP_EOL, FILE_APPEND);

                        echo fail;
                    }
                } else {
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '订单状态修改失败' . PHP_EOL, FILE_APPEND);
                    echo M('dingdan')->getLastSql();

                    echo fail;
                }
            }

        }

    }

    /**
     * 手机网站支付回调地址(信用卡付款)
     */
    public function xyk_notify(){
        /* ceshi 数据**/
//        $data = file_get_contents('php://input');
//        $data = json_decode($data, true);
//        $_POST = $data;
        /***/
        $data = $_POST;
        $time = time();
        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 手机网站支付回调数据: ' . json_encode($data) . PHP_EOL, FILE_APPEND);

        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
            // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；


            // 1、将订单状态修改为成功
            $danhao = $_POST['out_trade_no'];
            $one = M('dingdan')->where(['danhao' => $danhao])->find();
            $shoukuanma_id = $one['shoukuanma_id'];

            if ($one['status'] == 1) {
                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').' 订单状态已修改' . PHP_EOL, FILE_APPEND);

            } else {

                $trade_no = $_POST['trade_no'];
                $buyer = $_POST['buyer_logon_id'];
                $seller = $_POST['seller_email'];
                $money = $_POST['total_amount'];
                $buyer_id = $_POST['buyer_id'];
                $seller_id = $_POST['seller_id'];
                // gather
                $uid = $one['uid'];
                $gather = M('gather')->where(['uid' => $uid])->find();

                if ($one['hk'] == 1) {//不回款--手动
                    $yh_money = $money * (100 - $gather['up_set2']) / 100;
                } else {
                    //用户订单收益 = 订单金额 × （回款费率 - 上级设定费率）

                    $selfRate = \Home\Model\PtdataModel::getUserTdRate('xyktd',$uid,$money);
                    if(empty($selfRate)){
                        $selfRate = 0;
                    }
                    $yh_money = $money * ($gather['path6'] - $selfRate) / 100;
//                    $yh_money   =$money*($gather['path5']-$gather['up_set2'])/100; //回款
                }

//        $total = $gather['money'] + $yh_money;
                $total = $gather['fenrun'] + $yh_money;
                $total = number_format($total, 2, '.', '');

                $id = M('dingdan')->where(['danhao' => $danhao])->save([
                    'trade_no' => $trade_no,
                    'buyer' => $buyer,
                    'seller' => $seller,
                    'seller_id' => $seller_id,
                    'status' => 1,
                    'pay_money' => $money,
                    'yh_money' => $yh_money
                ]);

                if ($id > 0) {
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改成功' . PHP_EOL, FILE_APPEND);

                    // 2、修改平台用户的余额；
                    // 判断是否要回款 不回款的用户余额=总*(1-费率)/100 -2
                    $total_money = floatval($total)+floatval($gather['yongjin']);

                    M('dingdan')->where(['danhao' => $danhao])->save([
                        't_money' => $total_money
                    ]);
                    // 修改平台用户余额
//                    $re = M('gather')->where(['id' => $gather['id']])->save(['fenrun' => $total]);
                    if (true) {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                        if ($one['hk'] == 1) {
                            //不回款不需制定
                        } else {
                            // 插播：制定对应的回款表
//                    $trans_money = $money * (1 - $gather['path5'] / 100);
                            //修改为 收款码设置的费率

                            //取出收款码回款费率
                            $shoukuanma = M('shoukuanma')->find($shoukuanma_id);
                            $ptdata = M('ptdata')->find(1);
                            $trans_money = $money * (1 - $shoukuanma['xyk'] / 100) - $ptdata['xyk_fee'];
                            $trans_money = number_format($trans_money, 2, '.', '');
                            //回款金额 = 订单金额 ×（100- 回款费率）

                            $out_biz_no = 'xy' . date("YmdHis") . rand(1000, 9999);
                            file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'pay_return2.php回款金额信息'.$trans_money . PHP_EOL, FILE_APPEND);

                            $trans_result = M('trans')->add([
                                'trade_no' => $trade_no,
                                'uid' => $uid,
                                'money' => $trans_money,
                                'buyer_id' => $buyer_id,
                                'out_biz_no' => $out_biz_no,
                                'shoukuanma_id' => $shoukuanma_id,
                                'account' => $money
                            ]);
                            if($trans_result){

                                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入成功' . PHP_EOL, FILE_APPEND);
                            }else{
                                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入失败' . PHP_EOL, FILE_APPEND);
                            }


                        }
                        // echo success;
                        // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%

                        $ptyh = M('ptyh')->find(['uid' => $one['uid']]);


                        self::settle2admin($trade_no, $seller_id, $money, $uid, 'xyk',$shoukuanma_id);
                        self::settle2user($trade_no, $seller_id, $money, $uid, $shoukuanma_id, 'xyk',$buyer_id);
                        $this->divide($danhao);

                    } else {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改失败' . PHP_EOL, FILE_APPEND);
                        echo fail;
                    }

                } else {
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改失败' . PHP_EOL, FILE_APPEND);
                    echo fail;
                }
            }
        }
    }

    /**
     * 当面付信用卡回调地址
     */
    public function dangmianxyk_notify(){
        /* ceshi 数据**/
//        $data = file_get_contents('php://input');
//        $data = json_decode($data, true);
//        $_POST = $data;
        /***/
        $data = $_POST;
        $time = time();
        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 当面付付款方式信用卡回调数据: ' . json_encode($data) . PHP_EOL, FILE_APPEND);

        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
            // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；


            // 1、将订单状态修改为成功
            $danhao = $_POST['out_trade_no'];
            $one = M('dingdan')->where(['danhao' => $danhao])->find();
            $shoukuanma_id = $one['shoukuanma_id'];

            if ($one['status'] == 1) {
                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').' 订单状态已修改' . PHP_EOL, FILE_APPEND);

            } else {

                $trade_no = $_POST['trade_no'];
                $buyer = $_POST['buyer_logon_id'];
                $seller = $_POST['seller_email'];
                $money = $_POST['total_amount'];
                $buyer_id = $_POST['buyer_id'];
                $seller_id = $_POST['seller_id'];
                // gather
                $uid = $one['uid'];
                $gather = M('gather')->where(['uid' => $uid])->find();

                if ($one['hk'] == 1) {//不回款--手动
                    $yh_money = $money * (100 - $gather['up_set2']) / 100;
                } else {
                    //用户订单收益 = 订单金额 × （回款费率 - 上级设定费率）

                    $selfRate = \Home\Model\PtdataModel::getUserTdRate('xyktd',$uid,$money);
                    if(empty($selfRate)){
                        $selfRate = 0;
                    }
                    $yh_money = $money * ($gather['path6'] - $selfRate) / 100;
//                    $yh_money   =$money*($gather['path5']-$gather['up_set2'])/100; //回款
                }


                $total = $gather['fenrun'] + $yh_money;
                $total = number_format($total, 2, '.', '');

                $id = M('dingdan')->where(['danhao' => $danhao])->save([
                    'trade_no' => $trade_no,
                    'buyer' => $buyer,
                    'seller' => $seller,
                    'seller_id' => $seller_id,
                    'status' => 1,
                    'pay_money' => $money,
                    'yh_money' => $yh_money
                ]);

                if ($id > 0) {
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改成功' . PHP_EOL, FILE_APPEND);

                    // 2、修改平台用户的余额；
                    // 判断是否要回款 不回款的用户余额=总*(1-费率)/100 -2
                    $total_money = floatval($total)+floatval($gather['yongjin']);

                    M('dingdan')->where(['danhao' => $danhao])->save([
                        't_money' => $total_money
                    ]);
                    // 修改平台用户余额
//                    $re = M('gather')->where(['id' => $gather['id']])->save(['fenrun' => $total]);
                    if (true) {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                        if ($one['hk'] == 1) {
                            //不回款不需制定
                        } else {
                            // 插播：制定对应的回款表
//                    $trans_money = $money * (1 - $gather['path5'] / 100);
                            //修改为 收款码设置的费率

                            //取出收款码回款费率
                            $shoukuanma = M('shoukuanma')->find($shoukuanma_id);
                            $ptdata = M('ptdata')->find(1);

                            $trans_money = $money * (1 - $shoukuanma['xyk'] / 100) - $ptdata['xyk_fee'];
                            $trans_money = number_format($trans_money, 2, '.', '');
                            //回款金额 = 订单金额 ×（100- 回款费率）

                            $out_biz_no = 'xy' . date("YmdHis") . rand(1000, 9999);

                            $trans_result = M('trans')->add([
                                'trade_no' => $trade_no,
                                'uid' => $uid,
                                'money' => $trans_money,
                                'buyer_id' => $buyer_id,
                                'out_biz_no' => $out_biz_no,
                                'shoukuanma_id' => $shoukuanma_id,
                                'account' => $money
                            ]);
                            if($trans_result){

                                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入成功' . PHP_EOL, FILE_APPEND);
                            }else{
                                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入失败' . PHP_EOL, FILE_APPEND);
                            }


                        }
                        // echo success;
                        // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%

                        $ptyh = M('ptyh')->find(['uid' => $one['uid']]);


                        self::settle2admin($trade_no, $seller_id, $money, $uid, 'xyk',$shoukuanma_id);
                        self::settle2user($trade_no, $seller_id, $money, $uid, $shoukuanma_id, 'xyk',$buyer_id);
                        $this->divide($danhao);

                    } else {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改失败' . PHP_EOL, FILE_APPEND);
                        echo fail;
                    }

                } else {
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改失败' . PHP_EOL, FILE_APPEND);
                    echo fail;
                }
            }
        }
    }


    /**
     * 当面付分账给平台
     * @param string $trade_no 支付宝交易号
     * @param int $seller_id 卖家支付宝用户号 2088开头
     * @param float $money_in 订单金额
     * @param int $uid 用户id
     * @param string $type 付款方式:xyk=信用卡,huabei=花呗，fkhb=风控花呗
     * @param int $shoukuanma_id 收款吗id
     */
    public static function settle2admin($trade_no, $seller_id, $money_in, $uid, $type,$shoukuanma_id)
    {
        file_put_contents("hb.txt", date('Y-m-d H:i:s') . $type .'调用当面付分账给平台' .$seller_id  . PHP_EOL, FILE_APPEND);

        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay = new \Alipay;

        if($type == 'huabei'){
            $kbsh = D('Kbsh')->where('user_id=' . $seller_id)->find();
            //店铺拿到的钱，店铺应该拿到1%
            $shop_money = ceil($money_in * $kbsh['rate2'])/100;

        }elseif($type == 'fkhb'){
            $kbsh = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();
            $shop_money = ceil($money_in * $kbsh['rate_out'])/100;


        }else{
            $kbsh = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();

            //店铺拿到的钱，店铺应该拿到1%
            $shop_money = ceil($money_in * $kbsh['rate_out'])/100;
        }
        file_put_contents("hb.txt", date('Y-m-d H:i:s') . $type .'店铺拿到的钱啊：' .$shop_money  . PHP_EOL, FILE_APPEND);

        $dingdan = M('dingdan')->where(['trade_no' => $trade_no])->find();
        //店铺提成记录
//        self::addShopLog($kbsh['id'],$shop_money,$dingdan['id']);

        $ptdata = M('ptdata')->find(1); //平台基础配置信息
        $shoukuanma = M('shoukuanma')->find($shoukuanma_id);
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号
//        $money_out = $money_in * (1 - $kbsh['rate2'] / 100);//需要进行分账的金额  比总金额少
//        $money_out = round($money_out, 2);   //两位小数  四舍五入


        //客户拿到金额= 套现金额(100- 码费率）%   -  单笔手续费3(后台设置)
        //平台拿到金额= 套现金额*代理自身基础费率 + 单笔手续费3(后台设置)
        //代理拿到金额=  套现金额（ 设置点位- 在平台的点位）%


        //平台分账金额
        if ($type == 'huabei') {
            $marate = $shoukuanma['hb'];
        } else {
            $marate = $shoukuanma['xyk'];
        }


        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '店铺拿到的钱：' . $shop_money . PHP_EOL, FILE_APPEND);

        //平台应该拿到=套现金额*代理收费费率+单笔3 -减去店铺费率*套现金额 //100*5%+3-1
        $moneyOut = ($money_in * $marate +  $ptdata['xyk_fee']*100 - $shop_money*100)/100;
        $money_out = price_format($moneyOut,2); //保留两位小数并且不四舍五入

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账给平台金额：' . $money_out . PHP_EOL, FILE_APPEND);

        $data = [
            'out_request_no' => $out_request_no,
            'money_out' => $money_out,
//            'sh_money' => $money_in * ($kbsh['rate'] - $kbsh['rate2']) / 100,
            'sh_money' => $shop_money,
            'time' => time(),
            'name' => $kbsh['name'],
            'uid' => $kbsh['uid'],
        ];

        $toAccount = D('Adata')->where(['id' => 1])->find();//平台收款支付宝，用户提现

        if ($type == 'huabei') {

            $adata = $kbsh;
        }elseif($type == 'fkhb'){
            //手机网站支付
            $adata = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();
            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '风控花呗接口账号资料：' . json_encode($adata) . PHP_EOL, FILE_APPEND);

        } else {
            //手机网站支付
            $adata = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();

            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '信用卡支付接口账号资料：' . json_encode($adata) . PHP_EOL, FILE_APPEND);

        }

        M('dingdan')->where(['trade_no' => $trade_no])->save(['admin_money' => $money_out]);


//        D('Split')->where("trade_no='{$trade_no}'")->save($data);
        $royalty_parameters = [
            'trans_out' => "{$seller_id}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $toAccount['t_account'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => $money_out,   //分账出去的金额
            'desc' => '绿叶收银台服务中心-分账',
        ];
        $app_auth_token = '';
        file_put_contents("hb.txt", date('Y-m-d H:i:s')  .'当面付分账接口账号资料：' . json_encode($adata) . PHP_EOL, FILE_APPEND);

        $settleparams = [
            'out_request_no' => $out_request_no,
            'trade_no' => $trade_no,
            'royalty_parameters' => $royalty_parameters,
        ];
        file_put_contents("hb.txt", date('Y-m-d H:i:s')  .'当面付分账接口参数：' . json_encode($settleparams) . PHP_EOL, FILE_APPEND);

        $result = $qrpay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $adata);

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账-统一收单结算接口返回数据：分账平台' . json_encode($result) . PHP_EOL, FILE_APPEND);


        //状态:0=未支付,1=已支付,2=没分给平台,3=分给平台,4=没分给平台，分给客户,5=没分给平台，没分给客户，6=分给平台，没分给客户,7=分账成功
        if ($result->trade_no == $trade_no && empty($result->sub_msg)) {
            // 修改
//            D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1]);
////            // 增加余额
//            $gather = D('Gather')->where('uid=' . $kbsh['uid'])->find();
//            $money = $gather['money'] + $money_in * ($kbsh['rate'] - $kbsh['rate2']) / 100;
//            $sh_money = $money_in * ($kbsh['rate'] - $kbsh['rate2']) / 100;
//
////            $gather = D('Gather')->where('uid=' . $kbsh['uid'])->save(['money' => $money]);
//            D('Split')->where("trade_no='{$trade_no}'")->save(['t_money' => $money,'sh_money' => $shop_money, 'sub_msg' => '']);


            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给平台，接口返回成功' . PHP_EOL, FILE_APPEND);

            D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg' => $sub_msg]);
            \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],3);
        } else {
            $sub_msg = $result->sub_msg;
            if ($sub_msg == '接口返回错误') {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给平台，接口返回错误' . json_encode($result)  . PHP_EOL, FILE_APPEND);

                D('Kbsh')->where('user_id=' . $seller_id)->save(['use_status' => 0, 'cause' => $sub_msg . '//余额关闭,分账给平台失败', 'money' => $money_out]);
                D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1, 'sub_msg' => $sub_msg . '//已下架']);
                \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],2);
            } else {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给平台，接口返回成功' . PHP_EOL, FILE_APPEND);

                D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg' => $sub_msg]);
                \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],3);

            }

        }
    }


    /**
     * 当面付分账给用户
     * @param string $trade_no 支付宝交易号
     * @param int $seller_id 卖家支付宝用户号 2088开头
     * @param float $money_in 订单金额
     * @param int $uid 用户id
     * @param int $shoukuanma_id 收款码id
     * @param string $type 付款方式:xyk=信用卡,huabei=花呗
     * @param int $buyer_id 买家支付宝用户号,买家支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字
     */
    public static function settle2user($trade_no, $seller_id, $money_in, $uid, $shoukuanma_id, $type,$buyer_id)
    {
        $dingdan = M('dingdan')->where(['trade_no' => $trade_no])->find();

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . $type . '调用当面付分账给用户' . PHP_EOL, FILE_APPEND);
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');

        $qrpay = new \Alipay;
        $kbsh = D('Kbsh')->where('user_id=' . $seller_id)->find();
        $ptyh = M('ptyh')->find($uid);
        $ptdata = M('ptdata')->find(1); //平台基础配置信息
        $shoukuanma = M('shoukuanma')->find($shoukuanma_id);

        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号
//        $money_out = $money_in * (1 - $kbsh['rate2'] / 100);//需要进行分账的金额  比总金额少
//        $money_out = round($money_out, 2);   //两位小数  四舍五入

        //客户拿到金额= 套现金额(100- 码费率）%   -  单笔手续费3(后台设置)

        //平台分账金额
        if ($type == 'huabei') {
            $marate = $shoukuanma['hb'];
        } else {
            $marate = $shoukuanma['xyk'];
        }
        $money_out = $money_in * (100 - $marate) / 100 - $ptdata['xyk_fee'];
        $money_out = round($money_out,2);   //两位小数 四舍五入

        if($type == 'huabei'){
            $kbsh = D('Kbsh')->where('user_id=' . $seller_id)->find();
            //店铺拿到的钱，店铺应该拿到1%
            $shop_money = ceil($money_in * $kbsh['rate2'])/100;

        }elseif($type == 'fkhb'){
            $kbsh = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();
            $shop_money = ceil($money_in * $kbsh['rate_out'])/100;


        }else{
            $kbsh = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();

            //店铺拿到的钱，店铺应该拿到1%
            $shop_money = ceil($money_in * $kbsh['rate_out'])/100;
        }

        $data = [
            'out_request_no' => $out_request_no,
            'money_out' => $money_out,
//            'sh_money' => $money_in * ($kbsh['rate'] - $kbsh['rate2']) / 100,
            'sh_money' => $shop_money,
            'time' => time(),
            'name' => $kbsh['name'],
            'uid' => $kbsh['uid'],
        ];

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '用户拿到金额：' . $money_out . PHP_EOL, FILE_APPEND);


        if ($type == 'huabei') {
            $adata = $kbsh;
        }elseif($type == 'fkhb'){
            $adata = M('alipays')->where('pid=' . $seller_id)->order('id desc')->find();

        } else {
            //手机网站支付
            $adata = D('Alipays')->where(['pid' => $seller_id])->order('id desc')->find();
        }

        M('dingdan')->where(['trade_no' => $trade_no])->save(['user_money' => $money_out]);

//        D('Split')->where("trade_no='{$trade_no}'")->save($data);
        $royalty_parameters = [
            'trans_out' => "{$seller_id}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $buyer_id, //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => $money_out,   //分账出去的金额
            'desc' => '绿叶收银台服务中心-分账',
        ];
        $app_auth_token = '';
        $result = $qrpay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $adata);
        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '统一收单结算接口分账支付宝资料' . json_encode($adata) . PHP_EOL, FILE_APPEND);

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '统一收单结算接口返回数据：分账用户' . json_encode($result) . PHP_EOL, FILE_APPEND);

        //状态:0=未支付,1=已支付,2=没分给平台,3=分给平台,4=没分给平台，分给客户,5=没分给平台，没分给客户，6=分给平台，没分给客户,7=分账成功

        if ($result->trade_no == $trade_no && empty($result->sub_msg)) {
            // 修改
            D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1]);
            // 增加余额
            $gather = D('Gather')->where('uid=' . $kbsh['uid'])->find();
            $money = $gather['money'] + $money_in * ($kbsh['rate'] - $kbsh['rate2']) / 100;
            $gather = D('Gather')->where('uid=' . $kbsh['uid'])->save(['money' => $money]);
            //码商应该拿=套现金额（一级分润-共码费率）

//            D('Split')->where("trade_no='{$trade_no}'")->save(['t_money' => $money, 'sh_money' => $sh_money,'sub_msg' => '','status' => 1]);

            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给用户，接口返回成功：'. json_encode($result) . PHP_EOL, FILE_APPEND);

            D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg' => $sub_msg]);
            if($dingdan['status'] == 2){
                $status = 4;
            }else{
                $status = 7;
            }
            \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],$status);

            //updateDingdanFenzhangStatus


            //修改订单分账状态
            \Home\Logic\PayLogic::updateDingdanFenzhangStatus($dingdan['id'],1);
        } else {
            $sub_msg = $result->sub_msg;
            if ($sub_msg == '接口返回错误') {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给用户，接口返回错误:' . json_encode($result)  . PHP_EOL, FILE_APPEND);
                D('Kbsh')->where('user_id=' . $seller_id)->save(['use_status' => 0, 'cause' => $sub_msg . '//余额关闭,分账给用户失败', 'money' => $money_out]);
                D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1, 'sub_msg' => $sub_msg . '//已下架']);

                if($dingdan['status'] == 2){
                    $status = 5;
                }else{
                    $status = 6;
                }
                //更新订单状态
                \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],$status);
                //自动回款
                \Home\Logic\PayLogic::autoHuiKuan($dingdan['buyer_id'],$money_out,$dingdan['uid'],$qrpay);

                //更新分账状态
                \Home\Logic\PayLogic::updateDingdanFenzhangStatus($dingdan['id'],2);

            } else {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '调用当面付分账给用户，接口返回成功：'. json_encode($result) . PHP_EOL, FILE_APPEND);

                D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg' => $sub_msg]);
                if($dingdan['status'] == 2){
                    $status = 4;
                }else{
                    $status = 7;
                }
                \Home\Logic\PayLogic::updateDingdanStatus($dingdan['id'],$status);

                //updateDingdanFenzhangStatus


                //修改订单分账状态
                \Home\Logic\PayLogic::updateDingdanFenzhangStatus($dingdan['id'],1);



            }
        }
    }

    /**
     * 分润
     * @param string $danhao 单号
     */
    public function divide($danhao){
        $zhidu = \Home\Model\PtdataModel::getJiangLiZhiDu();
        $fenrunzhidu = \Home\Model\PtdataModel::getFenRunZhiDu();
        $ptdata = M('ptdata')->where(['id' => 1])->find();
        $dingdan = M('dingdan')->where(['danhao' => $danhao])->find();
        $shoukuanma = M('shoukuanma')->find($dingdan['shoukuanma_id']);
        $uid = $dingdan['uid'];
        $ptyh = D('Ptyh')->where("uid={$uid}")->find(); //当前订单用户
        $gather = D('Gather')->where("uid={$uid}")->find(); //当前订单用户


        //付款方式：1=信用卡,2=花呗,4=风控花呗,5=当面付信用卡
//        if(stripos($dingdan['danhao'],'hb') !== false){
////            类型：1=花呗，2=信用卡
//            $type =  1;
//        }else{
//            $type = 2;
//        }

        $type = $dingdan['pay_type'];
        //$dividetype 类型：0=默认，1=花呗分润，2=信用卡分润，3=团队奖励
        if($type == 1 || $type == 5){
            $dividetype = 2;

        }elseif($type == 2 || $type == 4){
            $dividetype = 1;
        }


        $pathArr = explode('/',$ptyh['path']);
        arsort($pathArr);
        $pathArr = array_values($pathArr);
//        dump($pathArr);exit;
        //1065/1066/1067/1068/1069/1070/1072
        if(!empty($pathArr)){
            $jiangliArr = [];
            foreach ($pathArr as $k => $v){

                if($k == 0){
                    //自身分润
                    //为给自己增加分润
                    //付款方式：1=信用卡,2=花呗,4=风控花呗,5=当面付信用卡
                    if($type == 1){
                        $set = $gather['up_set2'];
                        //类型：hbtd=花呗通道，fkhbtd=风控花呗，xyktd=信用卡通道
                        $tdrate = \Home\Model\PtdataModel::getUserTdRate('xyktd',$uid,$dingdan['pay_money']);
                        $rate = ($set*100 + $tdrate*100)/100;
                        $shoukuanmaRate = $shoukuanma['xyk'];

                    }elseif ($type == 4){
                        $set = $gather['up_set'];
                        //类型：hbtd=花呗通道，fkhbtd=风控花呗，xyktd=信用卡通道
                        $tdrate = \Home\Model\PtdataModel::getUserTdRate('fkhbtd',$uid,$dingdan['pay_money']);
                        $rate = ($set*100 + $tdrate*100)/100;
                        $shoukuanmaRate = $shoukuanma['hb'];
                    }elseif ($type == 5){
                        $set = $gather['up_set2'];
                        //类型：hbtd=花呗通道，fkhbtd=风控花呗，xyktd=信用卡通道
                        $tdrate = \Home\Model\PtdataModel::getUserTdRate('dmxyktd',$uid,$dingdan['pay_money']);
                        $rate = ($set*100 + $tdrate*100)/100;
                        $shoukuanmaRate = $shoukuanma['hb'];
                    }else{

                        $set = $gather['up_set'];
                        //类型：hbtd=花呗通道，fkhbtd=风控花呗，xyktd=信用卡通道
                        $tdrate = \Home\Model\PtdataModel::getUserTdRate('hbtd',$uid,$dingdan['pay_money']);
                        $rate = ($set*100 + $tdrate*100)/100;
                        $shoukuanmaRate = $shoukuanma['hb'];
                    }
                    $selfDivide = $dingdan['pay_money'] * ( $shoukuanmaRate- $rate ) / 100;
                    $selfDivide = number_format($selfDivide, 2, '.', '');

//                    put_file('分润数据：',[
//                        'shoukuanmaRate' => $shoukuanmaRate,
//                        'set' => $set,
//                        'tdrate' => $tdrate,
//                        'rate' => $rate,
//                        'selfDivide' => $selfDivide
//                    ]);

//                    dump([
//                        'shoukuanmaRate' => $shoukuanmaRate,
//                        'set' => $set,
//                        'tdrate' => $tdrate,
//                        'rate' => $rate,
//                        'selfDivide' => $selfDivide
//                    ]);exit;




                    //给自己分润
                    M('dividend')->add([
                        'uid' => $uid,
                        'danhao' => $dingdan['danhao'],
                        'trade_no' => $dingdan['trade_no'],
                        'shou' => $uid,
                        'parent' => '',
                        'total' => $dingdan['pay_money'],
                        'type' => $dividetype,
                        'level' => 0,
                        'divide' => $selfDivide,
                        'time' => time(),
                        'status' => 1,
                        't_money' => ($gather['money']*100 + $selfDivide*100)/100
                    ]);
                }else{
                    //两级代理基础点位的差值
                    $ptyhself = M('ptyh')->find($v);
                    $gatherself = M('gather')->where(['uid' => $v])->find();
                    $index = $k -1 ;
                    $upuid = $pathArr[$index];
                    $gatherup = M('gather')->where(['uid' => $upuid])->find();

                    $fenrunzhiduKeys = array_keys($fenrunzhidu);

//                    $totalsql = "SELECT count(*) FROM jd_ptyh AS p WHERE p.path LIKE '{$ptyhself['path']}' || '%' ";
//                    $totalCount = M('path')->query($totalsql);
                    $totalCount = \Home\Logic\UserLogic::getChildCount($ptyhself['path'],0);

                    //屏蔽点位升级奖励
                    /**
//                    $totalCount = 300;
                    if($type == 1 || $type == 5){

                        if($totalCount - $fenrunzhiduKeys[0] < 0){

                            $selfRate = $gatherself['up_set2'];
                        }elseif($totalCount - $fenrunzhiduKeys[0] >= 0 && $totalCount - $fenrunzhiduKeys[1] < 0 ){
                            $selfRate = ($gatherself['up_set2']*100 - $fenrunzhidu[$fenrunzhiduKeys[0]]*100)/100;

                        }else{
                            $selfRate = ($gatherself['up_set2']*100 - $ptdata['pt_rate2']*100)/100;
                        }
                        $divide = ( $gatherup['up_set2'] - $selfRate ) / 100 * $dingdan['pay_money'];

                    }elseif($type == 2 || $type == 4){
                        //花呗
                        if($totalCount - $fenrunzhiduKeys[0] < 0){

                            $selfRate = $gatherself['up_set'];
                        }elseif($totalCount - $fenrunzhiduKeys[0] >= 0 && $totalCount - $fenrunzhiduKeys[1] < 0 ){
                            $selfRate = ($gatherself['up_set']*100 - $fenrunzhidu[$fenrunzhiduKeys[0]]*100)/100;

                        }else{
                            $selfRate = ($gatherself['up_set']*100 - $ptdata['pt_rate']*100)/100;
                        }

                        $divide = ( $gatherup['up_set'] -  $selfRate ) / 100 * $dingdan['pay_money'];


                    }
                    //分润
                    M('dividend')->add([
                        'uid' => $v,
                        'danhao' => $dingdan['danhao'],
                        'trade_no' => $dingdan['trade_no'],
                        'shou' => $v,
                        'parent' => '',
                        'total' => $dingdan['pay_money'],
                        'type' => $dividetype,
                        'level' => $k,
                        'divide' => $divide,
                        'time' => time(),
                        'status' => 1,
                        't_money' => ($gatherself['money']*100 + $divide*100)/100
                    ]);

                    **/

                    //奖励
                    //        array(4) {
                    //            [300] => string(3) "0.2"
                    //            [1000] => string(3) "0.3"
                    //            [2000] => string(3) "0.4"
                    //            [3000] => string(3) "0.5"
                    //        }


                    $zhiduKeys = array_keys($zhidu);

                    if($totalCount - $zhiduKeys[0] >= 0 && $totalCount - $zhiduKeys[1] < 0){
                        $jiangliArr[$v] = $zhidu[$zhiduKeys[0]];

                    }elseif ($totalCount - $zhiduKeys[1] >= 0 && $totalCount - $zhiduKeys[2] < 0){
                        $jiangliArr[$v] = $zhidu[$zhiduKeys[1]];


                    }elseif ($totalCount - $zhiduKeys[2] >= 0 && $totalCount - $zhiduKeys[3] < 0){

                        $jiangliArr[$v] = $zhidu[$zhiduKeys[2]];

                    }elseif ($totalCount - $zhiduKeys[3] >= 0 ){
                        $jiangliArr[$v] = $zhidu[$zhiduKeys[3]];


                    }else{
                        //不满足奖励条件
                        $jiangliArr[$v] = 0;
                    }

                }

            }


            //团队奖励
            $this->reward($jiangliArr,$danhao);
        }


    }

    /**
     * 团队奖励
     * @param array $jiangliArr 奖励金额数组
     * @param string $danhao 订单单号
     *
     * array(6) {
    [1070] => string(3) "0.5"
    [1069] => string(3) "0.5"
    [1068] => string(3) "0.5"
    [1067] => string(3) "0.5"
    [1066] => string(3) "0.5"
    [1065] => string(3) "0.5"
    }
     */
    public function reward($jiangliArr,$danhao){
        $arr = kv2list($jiangliArr);
        $zhidu = \Home\Model\PtdataModel::getJiangLiZhiDu();
        $zhiduKeys = array_keys($zhidu);
        $endZhiduKeys = end($zhiduKeys);

        $jiangliValues = array_values($jiangliArr);
        array_shift($jiangliValues);
        $qitaSumValue = array_sum($jiangliValues);

        $ptdata = M('ptdata')->where(['id' => 1])->find();
        $jiangliAccount = $ptdata['xyk_jiangli'];

        /**
         * array(6) {
        [0] => array(2) {
        ["id"] => int(1070)
        ["value"] => string(3) "0.5"
        }
        [1] => array(2) {
        ["id"] => int(1069)
        ["value"] => string(3) "0.5"
        }
        [2] => array(2) {
        ["id"] => int(1068)
        ["value"] => string(3) "0.5"
        }
        [3] => array(2) {
        ["id"] => int(1067)
        ["value"] => string(3) "0.5"
        }
        [4] => array(2) {
        ["id"] => int(1066)
        ["value"] => string(3) "0.5"
        }
        [5] => array(2) {
        ["id"] => int(1065)
        ["value"] => string(3) "0.5"
        }
        }
         */
        foreach ($arr as $k => $v){
            if($k == 0){
                //直属上级
                if($v['value']*100 == $zhidu[$endZhiduKeys]*100){
                    $this->addJiangLi($v['id'],$danhao,$v['value']);
                    $jiangliAccount = 0;
                    break;
                }elseif($v['value']*100 == 0){
                    //不满足奖励条件
                }else{
                    $jiangliAccount = ($jiangliAccount*100 -  $v['value']*100)/100;

                    $this->addJiangLi($v['id'],$danhao,$v['value']);
                }

            }else{
                $divide = floor($v['value']/$qitaSumValue*$jiangliAccount*100)/100;
//                return ['xyk_jiangli' => $ptdata['xyk_jiangli'], 'qitaSum' => $qitaSumValue, 'value' => $v['value'], 'divide' => $divide,'jiangliAccount' => $jiangliAccount];
                $this->addJiangLi($v['id'],$danhao,$divide);
            }


        }


    }

    /**
     * @param int $uid 用户id
     * @param string $danhao 订单号
     * @param float $divide 金额
     */
    public function addJiangLi($uid,$danhao,$divide){
        $dingdan = M('dingdan')->where(['danhao' => $danhao])->find();
        $gather = M('gather')->where(['uid' => $uid])->find();

        M('dividend')->add([
            'uid' => $uid,
            'danhao' => $dingdan['danhao'],
            'trade_no' => $dingdan['trade_no'],
            'shou' => $uid,
            'parent' => '',
            'total' => $dingdan['pay_money'],
            'type' => 3, //团队奖励
            'level' => 0,
            'divide' => $divide,
            'time' => time(),
            'status' => 1,
            't_money' => ($gather['money']*100 + $divide*100)/100
        ]);
    }

    /**
     * 商户提成记录
     * @param int $kbsh_id 商户id
     * @param float $amount 金额
     * @param int $dingdan_id 订单id
     */
    public static function addShopLog($kbsh_id,$amount,$dingdan_id){
        M('shoplog')->add([
            'kbsh_id' => $kbsh_id,
            'amount' => $amount,
            'createtime' => time(),
            'dingdan_id' => $dingdan_id
        ]);
    }







}